package com.yx.study.leet.questionList.questionTwo;

import org.junit.Test;

/**
 * 58. 最后一个单词的长度
 * https://leetcode.cn/problems/length-of-last-word/description/
 */
public class Solution58 {
    public int lengthOfLastWord(String s) {
//        String[] a = s.trim().split(" ");
//        String b = a[a.length-1];
        // 双指针
        int length = s.length();
        int right = length - 1;
        // 倒序遍历,获取到最后一个单词尾部
        while (right >= 0 && s.charAt(right) == ' ') right--;
        // 正序遍历,获取到最后一个单词首部
        int left = right; // 最大长度
        while (left >= 0 && s.charAt(left) != ' ') left--;
        return right - left;
    }

    @Test
    public void test() {
        String s = "   fly me   to   the moon  ";
        System.out.println(lengthOfLastWord(s));
    }
}
